package com.panasonic.web.service.impl;

import com.panasonic.web.domain.cms.CmsCategory;
import com.panasonic.web.mapper.CmsCategoryMapper;
import com.panasonic.web.model.TreeModel;
import com.panasonic.web.service.ICmsCategoryService;
import com.panasonic.web.util.CmsSecurityUtils;
import com.panasonic.web.vo.CmsBatchStatusVo;
import com.panasonic.common.core.redis.RedisCache;
import com.panasonic.common.utils.DateUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 类目Service业务层处理
 *
 * @author lwf
 * @date 2021-11-12
 */
@Service
public class CmsCategoryServiceImpl implements ICmsCategoryService {

    private static final String CATEGORY_TREE = "category_tree";
    @Autowired
    private CmsCategoryMapper cmsCategoryMapper;

    @Autowired
    private RedisCache redisCache;

    /**
     * 查询类目
     *
     * @param categoryId 类目ID
     * @return 类目
     */
    @Override
    public CmsCategory selectCmsCategoryById(Long categoryId) {
        return cmsCategoryMapper.selectCmsCategoryById(categoryId);
    }

    /**
     * 查询类目列表
     *
     * @param cmsCategory 类目
     * @return 类目
     */
    @Override
    public List<CmsCategory> selectCmsCategoryList(CmsCategory cmsCategory) {
        return cmsCategoryMapper.selectCmsCategoryList(cmsCategory);
    }

    /**
     * 新增类目
     *
     * @param cmsCategory 类目
     * @return 结果
     */
    @Override
    public int insertCmsCategory(CmsCategory cmsCategory) {

        cmsCategory.setStatus("0");
        cmsCategory.setCreateTime(DateUtils.getNowDate());
        cmsCategory.setCreateBy(CmsSecurityUtils.getUsername());
        cmsCategory.setUpdateTime(DateUtils.getNowDate());
        cmsCategory.setUpdateBy(CmsSecurityUtils.getUsername());
        int n = cmsCategoryMapper.insertCmsCategory(cmsCategory);
        //更新parentids
        Long pid = cmsCategory.getParentId();
        CmsCategory p = null;
        if (pid == null) {
            p = cmsCategoryMapper.selectCmsCategoryById(pid);
        }
        String ancestors = "";
        if (p != null) {
            ancestors = p.getAncestors();
            ancestors += cmsCategory.getCategoryId() + ",";
        } else {
            ancestors = cmsCategory.getCategoryId() + ",";
        }
        cmsCategory.setAncestors(ancestors);
        n = cmsCategoryMapper.updateCmsCategory(cmsCategory);
        removeCacheData();
        return n;
    }

    /**
     * 修改类目
     *
     * @param cmsCategory 类目
     * @return 结果
     */
    @Override
    public int updateCmsCategory(CmsCategory cmsCategory) {
        cmsCategory.setUpdateTime(DateUtils.getNowDate());
        cmsCategory.setUpdateBy(CmsSecurityUtils.getUsername());
        removeCacheData();
        return cmsCategoryMapper.updateCmsCategory(cmsCategory);
    }

    /**
     * 批量删除类目
     *
     * @param categoryIds 需要删除的类目ID
     * @return 结果
     */
    @Override
    public int deleteCmsCategoryByIds(Long[] categoryIds) {
        removeCacheData();
        return cmsCategoryMapper.deleteCmsCategoryByIds(categoryIds);
    }

    /**
     * 删除类目信息
     *
     * @param categoryId 类目ID
     * @return 结果
     */
    @Override
    public int deleteCmsCategoryById(Long categoryId) {
        removeCacheData();
        return cmsCategoryMapper.deleteCmsCategoryById(categoryId);
    }
    @Override
    public int changeStatus(CmsBatchStatusVo cmsBatchStatusVo) {
        removeCacheData();

        return cmsCategoryMapper.changeStatus(cmsBatchStatusVo.getIds(),
                cmsBatchStatusVo.getStatus(),
                CmsSecurityUtils.getUsername(),
                DateUtils.getNowDate());
    }

    private void removeCacheData() {
        redisCache.deleteObject(CATEGORY_TREE);
    }

    @Override
    public List<TreeModel> getCategoryTree() {
        List<TreeModel> cacheList = redisCache.getCacheList(CATEGORY_TREE);
        if (CollectionUtils.isNotEmpty(cacheList)) {
            return cacheList;
        }
        List<TreeModel> treeModels = new ArrayList<>();
        CmsCategory cmsCategory = new CmsCategory();
        cmsCategory.setStatus("0");
        List<CmsCategory> cmsCategories = cmsCategoryMapper.selectCmsCategoryList(cmsCategory);
        if (CollectionUtils.isNotEmpty(cmsCategories)) {
            cmsCategories.stream().filter(s -> s.getParentId().equals(0L))
                    .sorted(Comparator.comparing(CmsCategory::getSort))
                    .forEach(s ->
                            treeModels.add(new TreeModel(s).setParentId(0L))
                    );
            treeModels.stream().forEach(s -> {
                List<TreeModel> childList = getCategoryTreeChild(s.getId(),
                        cmsCategories.stream().filter(c -> c.getParentId() > 0)
                                .sorted(Comparator.comparing(CmsCategory::getSort))
                                .collect(Collectors.toList()));
                s.setChildren(childList);
            });
        }
        return treeModels;
    }



    private List<TreeModel> getCategoryTreeChild(Long id, List<CmsCategory> collect) {
        List<TreeModel> list = new ArrayList<>();
        collect.stream().filter(s -> s.getParentId().equals(id)).forEach(s -> {
            TreeModel treeModel = new TreeModel(s).setParentId(id);
            list.add(treeModel);
        });
        list.stream().forEach(s -> {
            s.setChildren(getCategoryTreeChild(s.getId(), collect));
        });
        return list;
    }


}
